package com.xmb.wcapi.controller;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xmb.wcapi.cache.CommonCache;
import com.xmb.wcapi.constant.BaseEntry;
import com.xmb.wcapi.constant.DefaultValueConstant;
import com.xmb.wcapi.constant.R;
import com.xmb.wcapi.entity.BaseCommonDataDictionaryAndSet;
import com.xmb.wcapi.entity.BaseMaterial;
import com.xmb.wcapi.entity.CustomQualityData;
import com.xmb.wcapi.entity.InitialStock;
import com.xmb.wcapi.exception.InterfaceErrorException;
import com.xmb.wcapi.service.IBaseMaterialService;
import com.xmb.wcapi.service.ICustomQualityDataService;
import com.xmb.wcapi.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 自定义生产工单数据表 前端控制器
 * </p>
 *
 * @author huangping
 * @since 2024-07-25
 */
@Controller
@RequestMapping("/custom-quality-data")
public class CustomQualityDataController {

    @Autowired
    public CommonCache commonCache;

    @Resource
    IBaseMaterialService baseMaterialService;

    @Autowired
    private ICustomQualityDataService qualityDataService;

    @PostMapping("/add")
    @ResponseBody
    public R add(String url, String obj) {
        try {
            BaseEntry baseEntry = commonCache.init(url);
            setObj(baseEntry,obj);
            IService<Object> iService = baseEntry.getIService();
            List<BaseCommonDataDictionaryAndSet> collect = baseEntry.getSetList().stream().filter(e -> e.getUniqueness()).collect(Collectors.toList());
            if(collect.size() > 0){
                QueryWrapper<Object> ew = new QueryWrapper<>();
                for(BaseCommonDataDictionaryAndSet set : collect){
                    ew.eq(set.getTableField(), BeanUtil.getMethod(baseEntry.getData(), set.getEntityField()));
                }
                Object object = iService.getOne(ew);
                if(object != null) {
                    return R.error("请勿重复添加");
                }
            }
            for(BaseCommonDataDictionaryAndSet set : baseEntry.getSetList()){
                if(StringUtils.isNotEmpty(set.getDefaultValue())){
                    if(set.getDefaultValue().equals(DefaultValueConstant.user.getCode())){
                        BeanUtil.setMethod(baseEntry.getData(), set.getEntityField(), ShiroUtil.getUserId());
                    }else if(set.getDefaultValue().equals(DefaultValueConstant.date.getCode())){
                        BeanUtil.setMethod(baseEntry.getData(), set.getEntityField(), new Date());
                    }else if(set.getDefaultValue().equals(DefaultValueConstant.disable.getCode())){
                        BeanUtil.setMethod(baseEntry.getData(), set.getEntityField(), false);
                    }
                }
            }
            iService.save(baseEntry.getData());
            CustomQualityData bean = cn.hutool.core.bean.BeanUtil.toBean(baseEntry.getData(), CustomQualityData.class);
            //查找当前
            List<BaseMaterial> list = baseMaterialService.list(Wrappers.lambdaQuery(BaseMaterial.class).eq(BaseMaterial::getDjMaterial, bean.getMaterial()));
            if (!list.isEmpty()) {
                //查找当前料号的下一阶
                BaseMaterial baseMaterial = list.get(0);
                List<BaseMaterial> list1 = baseMaterialService.list(Wrappers.lambdaQuery(BaseMaterial.class).eq(BaseMaterial::getDjMaterial, baseMaterial.getDjMaterial()).eq(BaseMaterial::isChecked, true));
                //查询到就是下一级已经被勾选
                if (!list1.isEmpty()) {
                    bean.setQzclh(list1.get(0).getDjMaterial());
                }
            }
//            stockNowRecordService.balanceDataOne(bean.getMaterial(), DateUtil.format(new Date(),"yyyy-MM-dd"));
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("系统异常");
        }
        return R.ok();
    }

    private BaseEntry setObj(BaseEntry baseEntry, String obj) throws Exception {
        if(obj.contains("[{")) {
            baseEntry.setData(BeanUtil.parseObjToList(obj, Class.forName(baseEntry.getEntityClass())));
        }else {
            baseEntry.setData(BeanUtil.parseObjToBean(obj, Class.forName(baseEntry.getEntityClass())));
        }
        return baseEntry;
    }

    /**
     * 批量导入本地工单
     */
    @RequestMapping("/uploadCustomQuality")
    @ResponseBody
    public R uploadCustomQuality(String data) {
        if (StringUtils.isEmpty(data)){
            return R.error("未读取到数据");
        }
        List<CustomQualityData> list = JSONUtil.toList(data, CustomQualityData.class);
        if (list.isEmpty()){
            return R.error("excel数据解析失败！");
        }
        try {
            qualityDataService.uploadCustomQuality(list);
        } catch (InterfaceErrorException e) {
            return R.error(e.getMsg());
        }
        return R.ok();
    }

    @RequestMapping("/download_templet")
    @ResponseBody
    public void templet(HttpServletResponse response) {
        try {
            //excel表头
            List<TitleEntity> titleList=new ArrayList<>();
            titleList.add(new TitleEntity("0",null,"本地工单导入模板(工单日期不能小于今天)",null));
            titleList.add(new TitleEntity("1","0","自定义工单号",null));
            titleList.add(new TitleEntity("2","0","工单日期",null));
            titleList.add(new TitleEntity("3","0","料号",null));
            titleList.add(new TitleEntity("4","0","计划数",null));
            titleList.add(new TitleEntity("5","0","投入数",null));
            titleList.add(new TitleEntity("6","0","良品数",null));
            titleList.add(new TitleEntity("7","0","不良品数",null));
            titleList.add(new TitleEntity("8","0","不良分布",null));
            List<InitialStock> list = new ArrayList<>();
            ExcelTool excelTool = new ExcelTool("本地工单导入模板",20,20);
            List<Column>  titleData = excelTool.columnTransformer(titleList,"t_id","t_pid","t_content","t_fielName","0");
            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("本地工单导入模板.xls", "utf-8"));
            excelTool.exportExcel(titleData,list, response.getOutputStream(),true,true);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }


}

